package lol.clann.bukkit.pluginboot.model;

import lol.clann.clannboot.util.FileUtils;
import ninja.leaping.configurate.ConfigurationOptions;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.nutz.lang.Lang;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author pyz
 * @date 2018/8/17 上午7:28
 */
public class ConfigWrapper {

    private Path configPath;
    private ConfigurationLoader<CommentedConfigurationNode> configLoader;
    private CommentedConfigurationNode configNode;

    public ConfigWrapper(String path) {
        configPath = Paths.get(path);
        ensuerExist();
    }

    private void ensuerExist() {
        FileUtils.getOrCreateDir(configPath.getParent().toAbsolutePath().toString());
    }

    public void load() {
        ensuerExist();
        this.configLoader = HoconConfigurationLoader.builder()
                .setPath(configPath)
                .build();
        reload();
    }

    public void reload() {
        ensuerExist();
        ConfigurationOptions option = ConfigurationOptions.defaults().setShouldCopyDefaults(true);
        try {
            configNode = configLoader.load(option);
        } catch (IOException e) {
            throw Lang.wrapThrow(e);
        }
    }

    public void save() {
        try {
            ensuerExist();
            configLoader.save(configNode);
        } catch (IOException e) {
            throw Lang.wrapThrow(e);
        }
    }

    public ConfigurationLoader<CommentedConfigurationNode> getConfigLoader() {
        return configLoader;
    }


    public CommentedConfigurationNode getConfigNode() {
        return configNode;
    }
}
